package com.lagou.filter;

import com.lagou.config.RequestLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
public class BlackListFilter implements GlobalFilter , Runnable {
    private ConcurrentHashMap<String, List<Long>> requestMap = new ConcurrentHashMap<>();

    @Autowired
    RequestLimit requestLimit;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String hostString = exchange.getRequest().getRemoteAddress().getHostString();
        RequestPath path = exchange.getRequest().getPath();
        if(!path.value().substring(0,14).equals("/user/register")){
            return chain.filter(exchange);
        }
        if(!requestMap.containsKey(hostString)){
            requestMap.put(hostString,new CopyOnWriteArrayList<>());
        }
        List<Long> requestList = requestMap.get(hostString);
        System.out.println("***************"+hostString);
        //System.out.println(requestList.size());
        //请求次数超过限定次数
        /*if(requestList.size()>=requestLimit.getCount()){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.SEE_OTHER);
            String data = "您的请求过于频繁，请稍后再试";
            log.debug("=====>IP:" + hostString + " 请求过于频繁，被拒绝访问！");
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
        else{
            requestList.add(System.currentTimeMillis());
            requestMap.put(hostString,requestList);
        }*/
        return chain.filter(exchange);
    }

    @Override
    public void run() {
        Set<Map.Entry<String, List<Long>>> entries = requestMap.entrySet();
        for(Map.Entry<String,List<Long>> entry : entries){
            String requestHost = entry.getKey();
            List<Long> list = entry.getValue();
            for(int i=0;i<list.size();i++){
                if (list.get(i)<System.currentTimeMillis()-requestLimit.getTime()*1000){
                    list.remove(i);
                }
            }
            requestMap.put(requestHost, list);
        }
    }
}
